import time
import win32gui
import win32con
import pyautogui
import logging

# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - [ 小助手 ] : %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

logger = logging.getLogger(__name__)

# 获取窗口
def get_window_handle_by_title(title):
    handle = win32gui.FindWindow(None, title)
    return handle

# 屏幕截屏
def capture_window_screenshot(handle, filename):
    left, top, right, bottom = win32gui.GetWindowRect(handle)
    width = right - left
    height = bottom - top
    screenshot = pyautogui.screenshot(region=(left, top, width, height))
    screenshot.save(filename)
    logger.info("窗口截图已保存为: %s", filename)

# 窗口前置
def bring_window_to_front(handle):
    win32gui.ShowWindow(handle, win32con.SW_RESTORE)
    win32gui.BringWindowToTop(handle)
    win32gui.SetForegroundWindow(handle)

# 将窗口设置为指定大小
def set_window_size(handle, width, height):
    win32gui.SetWindowPos(handle, win32con.HWND_TOP, 0, 0, width, height, win32con.SWP_NOZORDER)

if __name__ == "__main__":
    window_title = "AstralParty"
    # 游戏是否运行
    game_running = False
    # 只提示一次
    is_tips_displayed = False

while True:
    handle = get_window_handle_by_title(window_title)
    if handle != 0:
        if not game_running:
            game_running = True
            is_tips_displayed = False
            logger.info("游戏已运行，正在加载配置")
            bring_window_to_front(handle)
            time.sleep(1)
            try:
                res = pyautogui.locateOnScreen('./images/control/Start.png')
                print(res)
            except pyautogui.ImageNotFoundException:
                logger.warning("未找到启动图标")
                # 在这里添加相应的处理逻辑
    else:
        if game_running:
            logger.warning("游戏已关闭")
            game_running = False
        elif not is_tips_displayed:
            logger.info("游戏未启动，等待游戏启动中...")
            is_tips_displayed = True
    time.sleep(1)  # 每隔一秒检查一次游戏是否运行
